package com.mtiiot.fstcpserver.fastdfs;

import com.mtiiot.fscore.bean.DfsFileAndNameValuePairsInfo;
import com.mtiiot.fscore.bean.DfsFileInfo;
import com.mtiiot.fscore.bean.FileInfo;
import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.bean.elasticsearch.metadata.FastdfsMetadata;
import com.mtiiot.fscore.bean.elasticsearch.metadata.LogMetadata;
import com.mtiiot.fscore.inter1.FastdfsService1;
import com.mtiiot.fscore.utils.LogLevel;
import com.mtiiot.fscore.utils.RequestType;
import com.mtiiot.fscore.utils.StringUtil;
import com.mtiiot.fscore.utils.SysName;
import com.mtiiot.fstcpserver.base.BaseService;
import com.mtiiot.fstcpserver.fastdfs.core.NameValuePair;
import com.mtiiot.fstcpserver.utils.Constants;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 分布式文件系统操作实现类
 * Created by lcy on 16-8-18.
 */
public class FastdfsServiceImpl1 extends BaseService implements FastdfsService1 {
    private static final Logger logger = LogManager.getLogger(FastdfsServiceImpl1.class);

    @Autowired
    private FastdfsBase fastdfsBase;

    /**
     * 存文件
     *
     * @param metadataInfo 元数据信息
     * @param ext          扩展名
     * @param file         文件名
     * @return
     */
    @Override
    public String storeFile(MetadataInfo metadataInfo, String ext, byte[] file) {
        String dfsKey=null;
        try{
            checkMetadata(metadataInfo);//验证元数据
            NameValuePair[] nvp =new NameValuePair[1];
            nvp[0]=new NameValuePair("ext",ext);
            dfsKey = fastdfsBase.uploadFile(file, ext,nvp);

            //元数据入队列
            FastdfsMetadata md=new FastdfsMetadata();
            setMetadataBeanData(metadataInfo,md,RequestType.INSERT.getName());
            double fileSize=file.length/1024;
            if(fileSize<1){
                fileSize=1;
            }
            md.setDfsId(dfsKey);
            md.setExt(ext);
            md.setFileSize(fileSize);
            metadataInQueue(Constants.TOPIC_METADATAINFO,Constants.TYPE_METADATA_FASTDFS,md);
            return dfsKey;
        }catch(Exception ex){
            //异常信息 元数据入reids队列
            handleException(Constants.MODULE_FASTDFS,"FastdfsServiceImpl1","storeFile",ex,logger);
            return dfsKey;
        }
    }

    /**
     * 取文件
     *
     * @param metadataInfo
     * @param dfsId
     * @return
     */
    @Override
    public DfsFileInfo getFile(MetadataInfo metadataInfo, String dfsId) {
        try{
            checkMetadata(metadataInfo);//验证元数据
            if(StringUtil.isEmpty(dfsId)){
                throw new Exception("dfsId 为空!");
            }
            byte[] file=fastdfsBase.downLoadFile(dfsId);
            if(file==null){
                return null;
            }
            NameValuePair nvp=fastdfsBase.getMetadata(dfsId)[0];
            int fileSize=file.length/1024;
            if(fileSize<1){
                fileSize=1;
            }
            DfsFileInfo dfsFileInfo=new DfsFileInfo();
            dfsFileInfo.setExt(nvp.getValue());
            dfsFileInfo.setFile(file);
            dfsFileInfo.setFileSize(fileSize);
            dfsFileInfo.setCrc32(fastdfsBase.getCrc32(dfsId));
            return dfsFileInfo;
        }catch(Exception ex){
            //异常信息 元数据入reids队列
            handleException(Constants.MODULE_FASTDFS,"FastdfsServiceImpl1","getFile",ex,logger);
            return null;
        }
    }


    /**
     * 存文件并且存入文件的附件信息
     * @param metadataInfo 元数据信息
     * @param ext 扩展名
     * @param file 文件字节数组
     * @param nameValuePairs 文件附加信息
     * @return
     */
    @Override
    public String storeFileAndNameValuePairs(MetadataInfo metadataInfo,String ext, byte[] file,Map<String,String> nameValuePairs){
        String dfsKey=null;
        try{
            checkMetadata(metadataInfo);//验证元数据
            NameValuePair[] nvp=null;
            if(nameValuePairs==null||nameValuePairs.size()==0){
                nvp =new NameValuePair[1];
                nvp[0]=new NameValuePair("ext",ext);
            }else{
                nvp =new NameValuePair[nameValuePairs.size()+1];
                nvp[0]=new NameValuePair("ext",ext);
                int i=1;
                for (String key:nameValuePairs.keySet()) {
                    nvp[i]=new NameValuePair(key,nameValuePairs.get(key));
                    i++;
                }
            }

            dfsKey = fastdfsBase.uploadFile(file, ext,nvp);

            //元数据入队列
            FastdfsMetadata md=new FastdfsMetadata();
            setMetadataBeanData(metadataInfo,md,RequestType.INSERT.getName());
            double fileSize=file.length/1024;
            if(fileSize<1){
                fileSize=1;
            }
            md.setDfsId(dfsKey);
            md.setExt(ext);
            md.setFileSize(fileSize);
            metadataInQueue(Constants.TOPIC_METADATAINFO,Constants.TYPE_METADATA_FASTDFS,md);
            return dfsKey;
        }catch(Exception ex){
            //异常信息 元数据入reids队列
            handleException(Constants.MODULE_FASTDFS,"FastdfsServiceImpl1","storeFileAndNameValuePairs",ex,logger);
            return dfsKey;
        }
    }


    /**
     * 取文件和文件的附加信息
     * @param metadataInfo 元数据信息
     * @param dfsId 存fastdfs的key
     * @return
     */
    @Override
    public DfsFileAndNameValuePairsInfo getFileAndNameValuePairs(MetadataInfo metadataInfo,String dfsId){
        try{
            checkMetadata(metadataInfo);//验证元数据
            if(StringUtil.isEmpty(dfsId)){
                throw new Exception("dfsId 为空!");
            }
            byte[] file=fastdfsBase.downLoadFile(dfsId);
            if(file==null){
                return null;
            }
            NameValuePair[] nameValuePairs=fastdfsBase.getMetadata(dfsId);
            int fileSize=file.length/1024;
            if(fileSize<1){
                fileSize=1;
            }
            DfsFileAndNameValuePairsInfo dfsFileInfo=new DfsFileAndNameValuePairsInfo();
            Map<String,String> map=new HashMap<String, String>();
            for(NameValuePair nvp:nameValuePairs){
                if(nvp.getName().equals("ext")){
                    dfsFileInfo.setExt(nvp.getValue());
                }else{
                    map.put(nvp.getName(),nvp.getValue());
                }
            }
            dfsFileInfo.setFile(file);
            dfsFileInfo.setFileSize(fileSize);
            dfsFileInfo.setNameValuePairs(map);
            dfsFileInfo.setCrc32(fastdfsBase.getCrc32(dfsId));
            return dfsFileInfo;
        }catch(Exception ex){
            //异常信息 元数据入reids队列
            handleException(Constants.MODULE_FASTDFS,"FastdfsServiceImpl1","getFileAndNameValuePairs",ex,logger);
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param metadataInfo
     * @param dfsId
     * @return
     */
    @Override
    public boolean delFile(MetadataInfo metadataInfo, String dfsId) {
        try{
            checkMetadata(metadataInfo);//验证元数据
            return fastdfsBase.deleteFile(dfsId);
        }catch(Exception ex){
            //异常信息 元数据入reids队列
            handleException(Constants.MODULE_FASTDFS,"FastdfsServiceImpl1","delFile",ex,logger);
            return false;
        }
    }
}